<template>
  <div class="app-container">
    <el-page-header @back="goBack" v-if="!flag">
    </el-page-header>
    <el-form v-if="flag"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      label-width="auto"
      v-show="showSearch"
    >
      <el-row>
        <el-form-item label="出库日期" style="width: 428px">
          <el-date-picker
            v-model="dateRange"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="YYYY/MM/DD ddd"
            value-format="YYYY-MM-DD HH:mm:ss"
            time-format="HH:mm:ss"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="领用机台" prop="machineId">
          <!-- <el-input
            v-model.trim="queryParams.machineName"
            style="width: 180px"
            placeholder="请输入领用机台"
            @keyup.enter="handleQuery"
          /> -->
          <el-select filterable v-model="queryParams.machineId">
            <el-option
              v-for="item in workbranchList"
              :label="item.name"
              :key="item.pid"
              :value="item.pid"
            ></el-option>
          </el-select>
        </el-form-item>
        <!--                <el-form-item label="是否领用" prop="weight">-->
        <!--                    <el-select v-model="queryParams.status">-->
        <!--                        <el-option-->
        <!--                            v-for="item in statusOptions"-->
        <!--                            :key="item.value"-->
        <!--                            :label="item.label"-->
        <!--                            :value="item.value"-->
        <!--                        ></el-option>-->
        <!--                    </el-select>-->
        <!--                </el-form-item>-->

        <div class="operation">
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          <el-button @click="advanced = !advanced">
            <a style="color: #448ef7">
              <el-icon v-if="advanced">
                <ArrowUpBold />
              </el-icon>
              <el-icon v-else>
                <ArrowDownBold />
              </el-icon>
            </a>
          </el-button>
          <right-toolbar
            style="margin-left: 10px"
            :search="false"
            v-model:showSearch="showSearch"
            @queryTable="getList"
            :columns="columns"
          ></right-toolbar>
        </div>
      </el-row>
      <el-row v-if="advanced">
        <el-form-item label="领用单编码" prop="useNum">
          <el-input
            v-model.trim="queryParams.useNum"
            style="width: 180px"
            placeholder="请输入领用单编码"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="生产单编码" prop="produceNo">
          <el-input
            v-model.trim="queryParams.produceNo"
            style="width: 180px"
            placeholder="请输入生产单编码"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="纸张名称" prop="name">
          <el-input
            v-model.trim="queryParams.name"
            style="width: 180px"
            placeholder="请输入纸张名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="纸张品牌" prop="brand">
          <el-select
            v-model="queryParams.brand"
            clearable
            filterable
            placeholder="请选择纸张品牌"
            style="width: 180px"
          >
            <el-option
              v-for="item in mes_paper_brand"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="规格型号" prop="specs">
          <el-select
            v-model="queryParams.specs"
            clearable
            placeholder="选择规格型号"
            style="width: 180px"
          >
            <el-option
              v-for="item in mes_paper_specs"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="定量" prop="weight">
          <el-input
            type="number"
            v-model.trim="queryParams.weight"
            style="width: 180px"
            clearable
            placeholder="请输入定量"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="厂/客料" prop="material">
          <el-select
            v-model="queryParams.material"
            clearable
            placeholder="选择厂/客料"
            style="width: 180px"
          >
            <el-option
              v-for="item in mes_paper_material"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select
            v-model="queryParams.unit"
            clearable
            placeholder="选择单位"
            style="width: 180px"
          >
            <el-option
              v-for="item in mes_paper_unit"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="幅宽" prop="longWide">
          <el-input
            v-model.trim="queryParams.longWide"
            clearable
            style="width: 180px"
            placeholder="请输入幅宽"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
      </el-row>
      <el-row :gutter="10" class="mb8" v-if="flag">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Download" @click="handleExport">
            导出
          </el-button>
        </el-col>
        <!--                <el-col :span="1.5">-->
        <!--                    <el-button type="primary" plain @click="handleSubmit()">领用执行</el-button>-->
        <!--                </el-col>-->
      </el-row>
    </el-form>
    <div>
      <el-table
        v-loading="loading"
        border
        :data="dataList"
        :summary-method="getSummaries"
        show-summary
      >
        <!--                <el-table-column type="selection" :reserve-selection="true" width="55" />-->
        <el-table-column label="序号" width="60" type="index" align="center" />
        <!--                <el-table-column-->
        <!--                    label="是否领用"-->
        <!--                    v-if="columns[5].visible"-->
        <!--                    align="center"-->
        <!--                    :show-overflow-tooltip="true"-->
        <!--                    prop="status"-->
        <!--                >-->
        <!--                    <template v-slot="{ row }">-->
        <!--                        {{ row.status == 1 ? '未领用' : '已领用' }}-->
        <!--                    </template>-->
        <!--                </el-table-column>-->
        <el-table-column
          v-if="columns[0].visible"
          label="领用单编码"
          min-width="200"
          align="center"
          prop="useNum"
          :show-overflow-tooltip="true"
        >
          <template v-slot="{ row }">
            <el-button type="primary" @click="handleViewCode(row)" text>
              {{ row.useNum }}
            </el-button>
          </template>
        </el-table-column>
        <!-- <el-table-column
                    v-if="columns[1].visible"
                    label="生产单编码"
                    min-width="200"
                    align="center"
                    prop="produceNo"
                    :show-overflow-tooltip="true"
                >
                    <template v-slot="{ row }">
                        <el-button type="primary" @click="handleViewOrderNo(row)" text>
                            {{ row.produceNo }}
                        </el-button>
                    </template>
                </el-table-column> -->
        <el-table-column
          v-if="columns[2].visible"
          label="领用机台编码"
          min-width="150"
          align="center"
          prop="machineNo"
          :show-overflow-tooltip="true"
        >
          <template v-slot="{ row }">
            <el-button type="primary" @click="handleViewMachineName(row)" text>
              {{ row.machineNo }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns[3].visible"
          label="机台名称"
          min-width="180"
          align="center"
          prop="machineName"
        />
        <el-table-column
          v-if="columns[4].visible"
          label="出库日期"
          min-width="180"
          align="center"
          prop="outboundDate"
          :show-overflow-tooltip="true"
        >
          <template v-slot="{ row }">
            {{ row.outboundDate ? row.outboundDate.split("T")[0] : "" }}
          </template>
        </el-table-column>
        <el-table-column
          label="纸型"
          v-if="columns[5].visible"
          align="center"
          :show-overflow-tooltip="true"
          prop="paperType"
        >
          <template #default="scope">
            <dict-tag :options="mes_paper_type" :value="scope.row.paperType" />
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns[6].visible"
          label="纸张编码"
          min-width="150"
          align="center"
          prop="code"
        >
          <template v-slot="{ row }">
            <el-button type="primary" @click="handleViewPaperCode(row)" text>
              {{ row.code }}
            </el-button>
          </template>
        </el-table-column>
        <!-- <el-table-column v-if="columns[7].visible" label="自有编码" min-width="120" align="center" prop="originalCode"
                    :show-overflow-tooltip="true" /> -->
        <el-table-column
          v-if="columns[8].visible"
          label="纸张名称"
          min-width="180"
          align="center"
          prop="name"
        />
        <el-table-column
          v-if="columns[9].visible"
          label="规格"
          min-width="120"
          align="center"
          prop="specs"
        >
          <template #default="scope">
            <span v-if="scope.row.longWide">
              {{ scope.row.longWide }}
            </span>
            <span v-if="scope.row.specs">
              <dict-tag :options="mes_paper_specs" :value="scope.row.specs" />
            </span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns[10].visible"
          min-width="120"
          label="品牌"
          align="center"
          prop="brand"
        >
          <template #default="scope">
            <dict-tag :options="mes_paper_brand" :value="scope.row.brand" />
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns[11].visible"
          width="120"
          label="定量"
          align="center"
          prop="weight"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          v-if="columns[2].visible"
          label="厂/客料"
          min-width="120"
          align="center"
          prop="material"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            <dict-tag
              :options="mes_paper_material"
              :value="scope.row.material"
            />
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns[12].visible"
          width="100"
          label="单位"
          align="center"
          prop="unit"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            <dict-tag :options="mes_paper_unit" :value="scope.row.unit" />
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns[13].visible"
          fixed="right"
          min-width="120"
          label="领用数量"
          align="center"
          prop="useNumber"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          v-if="columns[14].visible"
          label="备注"
          align="center"
          prop="remark"
          :show-overflow-tooltip="true"
        />
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script setup name="order">
import { downLoadBlob } from "@/utils/ruoyi";
import useUserStore from "@/store/modules/user";
import {
  getUseDetaillist,
  editUseInfo,
  exportDetail,
} from "@/api/storage/paperAccess.js";
import { getList as getWorkBenchList } from "@/api/basicInfo/workbench";
import { readonly } from "vue";
import { toNumber } from "@/utils/ruoyi";
import useTagsViewStore from "@/store/modules/tagsView";
const tagsViewStore = useTagsViewStore();

const { proxy } = getCurrentInstance();
const loading = ref(true);
const dataList = ref([]);
const showSearch = ref(true);
const router = useRouter();
const route = useRoute();
const total = ref(0);
const advanced = ref(false);
const useNumberSum = ref(0);
const workbranchList = ref([]);
const multiple = ref(true);
const selectRow = ref([]);
const flag=ref(true);
const statusOptions = ref([
  { value: "0", label: "全部" },
  { value: "1", label: "未领用" },
  { value: "2", label: "已领用" },
]);
//const   selected=ref("1");

// 列显隐信息
const columns = ref([
  { key: 0, label: `领用单编码`, visible: true },
  { key: 1, label: `生产单编码`, visible: true },
  { key: 2, label: `领用机台编码`, visible: true },
  { key: 3, label: `机台名称`, visible: true },
  { key: 4, label: `出库日期`, visible: true },
  { key: 5, label: `纸型`, visible: true },
  { key: 6, label: `纸张编码`, visible: true },
  { key: 7, label: `自有编码`, visible: true },
  { key: 8, label: `纸张名称`, visible: true },
  { key: 9, label: `规格型号`, visible: true },
  { key: 10, label: `品牌`, visible: true },
  { key: 11, label: `定量`, visible: true },
  { key: 12, label: `单位`, visible: true },
  { key: 13, label: `领用数量`, visible: true },
  { key: 14, label: `备注`, visible: true },
]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 30,
    status: "2",
  },
});
// 合计
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    switch (column.property) {
      case "useNumber":
        sums[index] = useNumberSum.value;
        break;
      default:
        break;
    }
  });
  return sums;
};

const getWorkList = () => {
  let model = undefined;
  const permissions = useUserStore().roles;
  if (permissions.includes("ddcq")) {
    model = "1";
  } else if (permissions.includes("zzzzc")) {
    model = "2";
  }
  getWorkBenchList({ pageNum: 1, pageSize: 200, model }).then((resp) => {
    resp.rows.forEach((item) => {
      item.name =
        item.machineName + "/" + (item.workshopName ? item.workshopName : "");
    });
    workbranchList.value = resp.rows;
  });
};
getWorkList();
// 提交
const handleSubmit = () => {
  selectRow.value
    .forEach((item) => {
      if (item.status != 2) {
        editUseInfo({ status: 2, id: item.useinfoId });
      } else {
        proxy.$modal.msgError("已领用不能再次领用");
      }
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("领用成功");
    })
    .catch(() => {});
};
const getDateNow = () => {
  var myDate = new Date();
  var year = myDate.getFullYear();
  var month = myDate.getMonth() + 1; //获取当前月份(0-11,0代表1月，所以要加1);
  var day = myDate.getDate(); //获取当前日（1-31）
  if (month < 10) {
    month = "0" + month;
  }
  if (day >= 0 && day <= 9) {
    day = "0" + day;
  }
  var firstDay = year + "-" + month + "-01" + " 00:00:00";
  return firstDay;
};
const getCurrentDay = () => {
  var now = new Date();
  var year = now.getFullYear();
  var month = now.getMonth() + 1; // 月份从0开始，需要加1
  var day = now.getDate();
  if (month < 10) {
    month = "0" + month;
  }

  if (day >= 0 && day <= 9) {
    day = "0" + day;
  }
  console.log(day);
  const currentDay = year + "-" + month + "-" + day + " 23:59:59";
  return currentDay;
};
const dateRange = ref([getDateNow(), getCurrentDay()]);
const { queryParams } = toRefs(data);
const {
  mes_paper_type,
  mes_paper_specs,
  mes_paper_brand,
  mes_paper_unit,
  mes_paper_material,
} = proxy.useDict(
  "mes_paper_type",
  "mes_paper_specs",
  "mes_paper_brand",
  "mes_paper_unit",
  "mes_paper_material"
);

const getList = () => {
  loading.value = true;

  if(route.query?.code){
    queryParams.value.code=route.query.code;
    queryParams.value.startDate=route.query.startDate;
    queryParams.value.endDate=route.query.endDate;
    queryParams.value.workshopName=route.query.workshopName;
    flag.value=false;
  }else{
    queryParams.value.startDate= Array.isArray(dateRange.value) ? dateRange.value[0] : undefined;
    queryParams.value.endDate=Array.isArray(dateRange.value) > 0 ? dateRange.value[1] : undefined;
  }
  const filteredData = Object.fromEntries(
    Object.entries(queryParams.value).filter(
      ([key, value]) => value !== null && value !== undefined && value !== ""
    )
  );
  getUseDetaillist(filteredData)
    .then((res) => {
      loading.value = false;
      if (res.rows.length > 0) {
        res.rows[0].useNumberSum = 0;
        res.rows.forEach((row) => {
          res.rows[0].useNumberSum =
            res.rows[0].useNumberSum + Number(row.useNumber || 0);
        });
        useNumberSum.value = toNumber(res.rows[0].useNumberSum, 3);
      }
      dataList.value = res.rows;
      total.value = res.total;
    })
    .catch((err) => {
      loading.value = false;
    });
};

// 搜索
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = [getDateNow(), getCurrentDay()];
  proxy.resetForm("queryRef");
  handleQuery();
};

const handleViewCode = (row) => {
  router.push({
    path: "/storage/paperAccess/accessDetails",
    query: {
      code: row.useNum,
      id: row.useinfoId,
      info: true,
    },
  });
};
// 查看纸张
const handleViewPaperCode = (row) => {
  router.push({
    path: "/basicInfo/paperCoding/details",
    query: {
      code: row.code,
      id: row.paperId,
      readonly: true,
    },
  });
};
// // 查看机台
const handleViewMachineName = (row) => {
  router.push({
    path: "/basicInfo/workbench/details",
    query: {
      id: row.machineId,
      info: true,
    },
  });
};

// 选中
const handleSelectionChange = (row) => {
  selectRow.value = row;
};
// 查看生产单
const handleViewOrderNo = (row) => {
  if (row.produceNo.indexOf("FM") > -1) {
    router.push({
      path: "/production/cover/coverDetails",
      query: {
        id: row.produceId,
        info: true,
        readonly: true,
        moduleCode: "searchAccess",
      },
    });
  } else {
    router.push({
      path: "/production/text/textDetails",
      query: {
        id: row.produceId,
        info: true,
        readonly: true,
        moduleCode: "searchAccess",
      },
    });
  }
};

// 导出
const handleExport = () => {
  exportDetail({
    ...queryParams.value,
    startDate: Array.isArray(dateRange.value) ? dateRange.value[0] : undefined,
    endDate:
      Array.isArray(dateRange.value) > 0 ? dateRange.value[1] : undefined,
  }).then((res) => {
    downLoadBlob(res, "领用明细单列表");
  });
};

getList();
// router.beforeEach((to, from, next) => {
//     if (to.path == "/basicInfo/personnel") {
//         getList()
//     }
//     next();
// });

//  返回
const goBack = () => {
  setTimeout(() => {
    router.go(-1);
    tagsViewStore.delView(route);
  }, 0);
};
</script>

<style lang="scss" scoped>
.operation {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 18px;
}
</style>
